package com.tars.txtm.aspect;

import com.tars.txtm.annotation.GlobalTransactional;
import com.tars.txtm.enums.TxEnum;
import com.tars.txtm.trasactional.MyTransactional;
import com.tars.txtm.trasactional.MyTransactionalManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author: Franz 2022/3/19
 * 自定义事务切面
 */
@Aspect
@Component
public class GlobalTransactionalAspect implements Ordered {

    @Around("@annotation(com.tars.txtm.annotation.GlobalTransactional)")
    public void invoke(ProceedingJoinPoint joinPoint){
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        GlobalTransactional annotation = method.getAnnotation(GlobalTransactional.class);

        //1.添加or创建事务分组
        String txGroupID;
        boolean start = annotation.isStart();
        if(start){
            txGroupID = MyTransactionalManager.createTxGroupID();
        }else {
            txGroupID = MyTransactionalManager.getCurrentTxGroupID();
        }

        //2.创建自定义事务
        MyTransactional transactional = MyTransactionalManager.createTransaction(txGroupID,annotation.txCount());

        try {
            joinPoint.proceed();
            transactional.setStatus(TxEnum.commit);
        } catch (Throwable throwable) {
            transactional.setStatus(TxEnum.rollback);
        }

        //3.提交事务到远程分组
        MyTransactionalManager.addTransaction(transactional,annotation.isEnd());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
